package com.ay.selfservicemachine.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

public class JsonUtils {


    private Gson gson;

    private JsonUtils() {
        gson = new Gson();
    }

    private static class Holder {
        static JsonUtils mInstance = new JsonUtils();
    }

    public static JsonUtils getInstance() {
        return Holder.mInstance;
    }

    public Gson getGson() {
        return gson;
    }


    public static <T> T fromJson(String str,Class<T> tClass) {
        return Holder.mInstance.gson.fromJson(str, tClass);
    }

    public static <T> List<T> fromJson(String str) {
        return Holder.mInstance.gson.fromJson(str, new TypeToken<List<T>>() {
        }.getType());
    }

    public static String toJson(Object obj,Class<?> tClass) {
        return Holder.mInstance.gson.toJson(obj, tClass);
    }

    public static <T> String toJson(T obj) {
        return Holder.mInstance.gson.toJson(obj, new TypeToken<T>() {
        }.getType());
    }

    //http get
    public static String toUrl(String str) throws JSONException {
        JSONObject json = new JSONObject(str);
        StringBuffer sb = new StringBuffer();
        Iterator<String> keys = json.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            sb.append("&").append(key);
            if (json.get(key) instanceof String
                    || json.get(key) instanceof Number
                    || json.get(key) instanceof Boolean
                    || json.get(key) instanceof JSONObject
                    || json.get(key) instanceof JSONArray) {
                sb.append("=").append(json.get(key));
            } else {
                sb.append("=").append("null");
            }
        }
        return sb.toString();
    }

}
